package com.CRApp.controller;

import com.CRApp.pojo.Article;
import com.CRApp.pojo.ArticleHistory;
import com.CRApp.pojo.Result;
import com.CRApp.service.ArticleService;
import com.CRApp.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: ArticleController
 * @Author : LuoFan洛樊
 * @Date : 2025/2/20 - 10:58
 * Description : 文章控制器
 */
@RestController
@CrossOrigin
@RequestMapping("/essay")
public class ArticleController {
    
    @Autowired
    private ArticleService articleService;
    
    @GetMapping("/list")
    public Result<List<Article>> list() {
        List<Article> articleList = articleService.getEssayList();
        return Result.success(articleList);
    }
    
    @PostMapping("/search")
    public Result<List<Article>> search(@RequestBody Map<String, String> params) {
        String keyword = params.get("keyword");
        List<Article> articles = articleService.search(keyword);
        return Result.success(articles);
    }

    @PostMapping("/detail")
    public Result getArticleDetail(@RequestParam Integer id, @RequestParam(required = false) Integer userId) {
        try {
            Article article = articleService.getEssayById(id);
            if (article == null) {
                return Result.error("文章不存在");
            }

            // 如果userId不为null，则记录浏览历史
            if (userId != null) {
                try {
                    articleService.addHistory(userId, id);
                } catch (Exception e) {
                    // 记录历史失败，但不影响文章内容返回
                    e.printStackTrace();
                }
            }
            
            return Result.success(article);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取文章失败");
        }
    }

    // 获取用户收藏的文章列表
    @GetMapping("/collections")
    public Result<List<Article>> getCollections() {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");
        
        List<Article> collections = articleService.getUserCollections(currentUserId);
        return Result.success(collections);
    }

    // 收藏/取消收藏文章
    @PostMapping("/collect")
    public Result<String> toggleCollection(@RequestParam Integer articleId) {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");
        
        // 先检查文章是否存在
        Article article = articleService.getEssayById(articleId);
        if (article == null) {
            return Result.error("文章不存在");
        }
        
        boolean isCollected = articleService.toggleCollection(currentUserId, articleId);
        return Result.success(isCollected ? "收藏成功" : "取消收藏成功");
    }

    // 检查文章是否已收藏
    @GetMapping("/isCollected")
    public Result<Boolean> checkCollection(@RequestParam Integer articleId) {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");
        
        boolean isCollected = articleService.isCollected(currentUserId, articleId);
        return Result.success(isCollected);
    }

    // 获取用户的文章浏览历史
    @GetMapping("/history")
    public Result<List<ArticleHistory>> getHistory() {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");
        
        List<ArticleHistory> history = articleService.getUserHistory(currentUserId);
        return Result.success(history);
    }

    // 清空浏览历史
    @DeleteMapping("/deleteHistry")
    public Result<String> clearHistory() {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");
        
        articleService.clearHistory(currentUserId);
        return Result.success("清空历史记录成功");
    }
}
